#import "GameViewController.h"
#import "ProgressView.h"

@interface GameViewController ()

@property (nonatomic, strong) GameEngine *gameEngine;
@property (nonatomic, strong) UIView *gameGrid;
@property (nonatomic, strong) UILabel *healthLabel;
@property (nonatomic, strong) UILabel *weaponLabel;
@property (nonatomic, strong) UILabel *killsLabel;
@property (nonatomic, strong) UILabel *bossLabel;
@property (nonatomic, strong) UIButton *restartButton;
@property (nonatomic, strong) UILabel *messageLabel;
@property (nonatomic, strong) ProgressView *progressViews;

@end

@implementation GameViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self setupGame];
    UIImageView* boss = [[UIImageView alloc] init];
    boss.frame = CGRectMake(self.view.frame.size.width/2-60, self.view.frame.size.height*0.1, self.view.frame.size.width-320, self.view.frame.size.height*0.30);
    boss.image = [UIImage imageNamed:@"boss"];
    boss.contentMode = UIViewContentModeScaleAspectFill;
    [self.view addSubview:boss];
    
    [self setupPregress];
}

- (void)setupPregress {
    // 创建进度条
    ProgressView *progressView = [[ProgressView alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2-100, self.view.frame.size.height*0.35, 200, 20)];

    self.progressViews = progressView;
    // 方法1：使用颜色
//    progressView.backgroundColor = [UIColor darkGrayColor];
//    progressView.progressColor = [UIColor redColor];

    // 方法2：使用图片（血量效果）
    progressView.backgroundImage = [UIImage imageNamed:@"血条底"];
    progressView.progressImage = [UIImage imageNamed:@"血条红"];

    // 设置边距
    progressView.progressInsets = UIEdgeInsetsMake(3, 3, 3, 3);

    // 添加到视图
    [self.view addSubview:progressView];

    // 设置进度（带动画）
    float progress = self.gameEngine.playerHealth/100;
    [progressView setProgress:progress animated:YES];

    // 定时更新进度（模拟血量变化）
//    [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
//        CGFloat randomProgress = (CGFloat)(arc4random_uniform(100)) / 100.0f;
//        [progressView setProgress:randomProgress animated:YES];
//    }];
    //绿色
    // 创建进度条
    ProgressView *progressView1 = [[ProgressView alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2-100, self.view.frame.size.height*0.35+30, 200, 20)];

    // 方法1：使用颜色
//    progressView.backgroundColor = [UIColor darkGrayColor];
//    progressView.progressColor = [UIColor redColor];

    // 方法2：使用图片（血量效果）
    progressView1.backgroundImage = [UIImage imageNamed:@"血条底"];
    progressView1.progressImage = [UIImage imageNamed:@"血条绿"];

    // 设置边距
    progressView1.progressInsets = UIEdgeInsetsMake(1, 1, 1, 1);

    // 添加到视图
    [self.view addSubview:progressView1];

    // 设置进度（带动画）
    [progressView1 setProgress:0.75 animated:YES];
}

- (void)setupUI {
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIImageView *drawbgIv=[[UIImageView alloc]initWithFrame:self.view.bounds];
    drawbgIv.contentMode = UIViewContentModeScaleAspectFill;
    drawbgIv.image=[UIImage imageNamed:@"bjgame"];
    [self.view addSubview:drawbgIv];
    
    // 状态显示
    self.healthLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 150, 150, 30)];
    self.healthLabel.textColor = [UIColor redColor];
    [self.view addSubview:self.healthLabel];
    
    self.weaponLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 180, 150, 30)];
    self.weaponLabel.textColor = [UIColor blueColor];
    [self.view addSubview:self.weaponLabel];
    
    self.killsLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 210, 150, 30)];
    self.killsLabel.textColor = [UIColor darkGrayColor];
    [self.view addSubview:self.killsLabel];
    
    self.bossLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 240, 200, 30)];
    self.bossLabel.textColor = [UIColor purpleColor];
    [self.view addSubview:self.bossLabel];
    
    // 消息显示
    self.messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 280, 300, 40)];
    self.messageLabel.textColor = [UIColor orangeColor];
    self.messageLabel.font = [UIFont boldSystemFontOfSize:16];
    [self.view addSubview:self.messageLabel];
    
    // 游戏网格
    CGFloat gridSize = self.view.bounds.size.width-20;
    CGFloat gridX = (self.view.bounds.size.width - gridSize) / 2;
    self.gameGrid = [[UIView alloc] initWithFrame:CGRectMake(gridX, self.view.bounds.size.height-gridSize-110, gridSize, gridSize)];
    self.gameGrid.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:self.gameGrid];
    
    // 重新开始按钮
    self.restartButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.restartButton.frame = CGRectMake(20, 560, 100, 40);
    [self.restartButton setTitle:@"重新开始" forState:UIControlStateNormal];
    [self.restartButton addTarget:self action:@selector(restartGame) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.restartButton];
    
    // 添加手势识别
    UISwipeGestureRecognizer *swipeUp = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
    swipeUp.direction = UISwipeGestureRecognizerDirectionUp;
    [self.view addGestureRecognizer:swipeUp];
    
    UISwipeGestureRecognizer *swipeDown = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
    swipeDown.direction = UISwipeGestureRecognizerDirectionDown;
    [self.view addGestureRecognizer:swipeDown];
    
    UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
    swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.view addGestureRecognizer:swipeLeft];
    
    UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
    swipeRight.direction = UISwipeGestureRecognizerDirectionRight;
    [self.view addGestureRecognizer:swipeRight];
}

- (void)setupGame {
    self.gameEngine = [[GameEngine alloc] init];
    self.gameEngine.delegate = self;
    [self updateStatsDisplay];
    [self createGridUI];
}

- (void)createGridUI {
    // 清除旧的网格视图
    for (UIView *subview in self.gameGrid.subviews) {
        [subview removeFromSuperview];
    }
    
    CGFloat cellSize = self.gameGrid.bounds.size.width / 4;
    
    for (NSInteger i = 0; i < 4; i++) {
        for (NSInteger j = 0; j < 4; j++) {
            UIImageView *cell = [[UIImageView alloc] initWithFrame:CGRectMake(j * cellSize, i * cellSize, cellSize, cellSize)];
            cell.userInteractionEnabled = true;
            cell.backgroundColor = [UIColor whiteColor];
            cell.layer.borderWidth = 1;
            cell.layer.borderColor = [UIColor blackColor].CGColor;
            
            Position *pos = [[Position alloc] initWithRow:i column:j];
            GridItem *item = [self.gameEngine gridItemAtPosition:pos];
            
            UILabel *label = [[UILabel alloc] initWithFrame:cell.bounds];
            label.textAlignment = NSTextAlignmentCenter;
            label.font = [UIFont boldSystemFontOfSize:14];
            [cell addSubview:label];
            
            [self updateCell:cell withGridItem:item];
            
            [self.gameGrid addSubview:cell];
        }
    }
}

- (void)updateCell:(UIImageView *)cell withGridItem:(GridItem *)item {
    UILabel *label = cell.subviews.firstObject;
    switch (item.type) {
        case GridTypePlayer:
            cell.contentMode = UIViewContentModeScaleAspectFill;
            cell.image = [UIImage imageNamed:@"角色"];
//            cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"角色"]];
            label.text = @"玩家";
            label.textColor = [UIColor blackColor];
            break;
        case GridTypeWeapon:
            cell.contentMode = UIViewContentModeScaleAspectFill;
            cell.image = [UIImage imageNamed:@"武器"];
//            cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"武器"]];
            label.text = [NSString stringWithFormat:@"武器%ld", (long)item.value];
            label.textColor = [UIColor whiteColor];
            break;
        case GridTypeHealthPotion:
            cell.contentMode = UIViewContentModeScaleAspectFill;
            cell.image = [UIImage imageNamed:@"血瓶"];
//            cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"血瓶"]];
            label.text = [NSString stringWithFormat:@"血瓶%ld", (long)item.value];
            label.textColor = [UIColor whiteColor];
            break;
        case GridTypeEnemy:
            cell.contentMode = UIViewContentModeScaleAspectFill;
            cell.image = [UIImage imageNamed:@"怪物"];
//            cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"怪物"]];
            label.text = [NSString stringWithFormat:@"敌人%ld", (long)item.value];
            label.textColor = [UIColor blackColor];
            break;
        case GridTypeBoss:
            cell.backgroundColor = [UIColor purpleColor];
            label.text = @"BOSS";
            label.textColor = [UIColor whiteColor];
            break;
        default:
            cell.backgroundColor = [UIColor whiteColor];
            label.text = @"";
            break;
    }
}

- (void)handleSwipe:(UISwipeGestureRecognizer *)gesture {
    if (self.gameEngine.gameState != GameStatePlaying) return;
    
    Position *newPosition = [self.playerPosition copy];
    
    switch (gesture.direction) {
        case UISwipeGestureRecognizerDirectionUp:
            newPosition.row = MAX(0, newPosition.row - 1);
            break;
        case UISwipeGestureRecognizerDirectionDown:
            newPosition.row = MIN(3, newPosition.row + 1);
            break;
        case UISwipeGestureRecognizerDirectionLeft:
            newPosition.column = MAX(0, newPosition.column - 1);
            break;
        case UISwipeGestureRecognizerDirectionRight:
            newPosition.column = MIN(3, newPosition.column + 1);
            break;
        default:
            break;
    }
    
    [self.gameEngine movePlayerToPosition:newPosition];
}

- (void)updateStatsDisplay {
    dispatch_async(dispatch_get_main_queue(), ^{
        float progress = self.gameEngine.playerHealth/100.00;
        [self.progressViews setProgress:progress animated:YES];
    });
    
    self.healthLabel.text = [NSString stringWithFormat:@"生命值: %ld", (long)self.gameEngine.playerHealth];
    self.weaponLabel.text = [NSString stringWithFormat:@"武器点数: %ld", (long)self.gameEngine.playerWeapon];
    self.killsLabel.text = [NSString stringWithFormat:@"击败敌人: %ld", (long)self.gameEngine.enemiesKilled];
    self.bossLabel.text = [NSString stringWithFormat:@"Boss血量: %ld/40", (long)self.gameEngine.bossHealth];
}

- (void)restartGame {
    [self.gameEngine restartGame];
    [self createGridUI];
    self.messageLabel.text = @"";
}

#pragma mark - GameEngineDelegate

- (void)gameStateDidChange {
    switch (self.gameEngine.gameState) {
        case GameStateWin:
            self.messageLabel.text = @"胜利! 点击重新开始新游戏";
            break;
        case GameStateLose:
            self.messageLabel.text = @"失败! 点击重新开始新游戏";
            break;
        default:
            break;
    }
}

- (void)gridDidUpdateAtPosition:(Position *)position {
    [self createGridUI]; // 简单实现，刷新整个网格
}

- (void)playerStatsDidChange {
    [self updateStatsDisplay];
}

- (void)showMessage:(NSString *)message {
    self.messageLabel.text = message;
    
    // 3秒后清除消息
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if ([self.messageLabel.text isEqualToString:message]) {
            self.messageLabel.text = @"";
        }
    });
}

- (Position *)playerPosition {
    return self.gameEngine.playerPosition;
}

@end
